﻿using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
using DevExpress.LookAndFeel;
using DevExpress.XtraEditors;
using S3.Biz;
using S3.Common;

namespace S3
{
    public partial class LoginForm : S3FormBase

    {
        #region Public members

        public bool IsLoginned { get; set; }

        #endregion

        private readonly BackgroundWorker _backgroundWorker;
        private MainForm _ownerForm;

        public LoginForm(Form lisenceForm)
        {
            IsLoginned = false;
            InitializeComponent();

            _backgroundWorker = new BackgroundWorker();
            _backgroundWorker.DoWork += BackgroundWorkerDoWork;
            _backgroundWorker.RunWorkerCompleted += BackgroundWorkerRunWorkerCompleted;

            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "LisenceForm")
                {
                    f.Hide();
                }
            }

            Show();
        }

        public LoginForm()
        {
            IsLoginned = false;
            InitializeComponent();

            _backgroundWorker = new BackgroundWorker();
            _backgroundWorker.DoWork += BackgroundWorkerDoWork;
            _backgroundWorker.RunWorkerCompleted += BackgroundWorkerRunWorkerCompleted;

            InitActionMapping();
        }

        #region Actions Key        

        public static void InitActionMapping()
        {
            //try
            //{
            //    var setting = ConfigurationSettings.AppSettings;
            //    ActionMapping.Add(setting[Convert.ToString(ActionType.AddService)], Convert.ToString(ActionType.AddService));
            //    ActionMapping.Add(setting[Convert.ToString(ActionType.ChangeBlock)], Convert.ToString(ActionType.ChangeBlock));
            //    ActionMapping.Add(setting[Convert.ToString(ActionType.ChangeDesk)], Convert.ToString(ActionType.ChangeDesk));
            //    ActionMapping.Add(setting[Convert.ToString(ActionType.ChangeMachineQuantity)], Convert.ToString(ActionType.ChangeMachineQuantity));
            //    ActionMapping.Add(setting[Convert.ToString(ActionType.ChangeService)], Convert.ToString(ActionType.ChangeService));
            //    ActionMapping.Add(setting[Convert.ToString(ActionType.ChangeType)], Convert.ToString(ActionType.ChangeType));
            //    ActionMapping.Add(setting[Convert.ToString(ActionType.StartMachine)], Convert.ToString(ActionType.StartMachine));
            //    ActionMapping.Add(setting[Convert.ToString(ActionType.StopMachine)], Convert.ToString(ActionType.StopMachine));
            //}
            //catch (Exception ex)
            //{
            //    throw new Exception(ex.Message);
            //}
        }

        #endregion

        #region BackGroundWorker

        private bool _isOpenMainForm;

        public void ThreadProc()
        {
            DevExpress.UserSkins.OfficeSkins.Register();   
            Application.Run(new MainForm{LoginFrm = this});
        }

        private void BackgroundWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            var result = (LoginStatus) e.Result;
            EnableControls(true);
            _isOpenMainForm = false;
            switch (result)
            {
                case LoginStatus.Successful:
                    {
                        _isOpenMainForm = true;

                        //Close Login form.
                        FormCollection openForms = Application.OpenForms;

                        foreach (Form f in openForms)
                        {
                            if (f.Text == Constants.MainFormTitle)
                            {
                                _isOpenMainForm = false;
                                break;
                            }
                        }
                        this.Close();
                    }
                    break;
                case LoginStatus.Wrong:
                    {
                        lblMsg.Text = "Tên đăng nhập hoặc Mật khẩu sai.";
                    }
                    break;
                case LoginStatus.Fail:
                    {
                        XtraMessageBox.Show("Có lỗi trong quá trình khởi động phần mềm: " + e.Error.Message);
                        Close();
                    }
                    break;
            }
        }

        private void BackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            var log = new LogHelper();
            try
            {                
                var args = (string[]) e.Argument;
                string userName = args[0];
                string password = args[1];

                log.WriteLog("Begin Login");

                using (var manager = new UserManager())
                {
                    log.WriteLog("Called UserManager");

                    if (manager.Login(userName, password))
                    {
                        Constants.StaffName = userName;
                        IsLoginned = true;
                        //LoadPrinterTemplate();
                        e.Result = LoginStatus.Successful;
                    }
                    else
                    {
                        e.Result = LoginStatus.Wrong;
                    }
                }
            }
            catch (Exception ex)
            {
                log.WriteLog("backgroundWorker_DoWork " + ex.Message);

                e.Result = LoginStatus.Fail;
            }
        }

        #endregion

        public void ClearForm()
        {
            txtPassword.Text = string.Empty;
            txtUserName.Text = string.Empty;
        }

        //private static void LoadPrinterTemplate()
        //{
        //    var path = Path.Combine(Application.StartupPath, "data\\"+Properties.Resources.BillTemplate);
        //    if (File.Exists(path))
        //    {
        //        var content = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
        //        var contentStream = new StreamReader(content);
        //        Constants.BillContent = contentStream.ReadToEnd();
        //    }
        //}
        private void LoginFormClosing(object sender, FormClosingEventArgs e)
        {
            if (_isOpenMainForm)
            {
                var t = new Thread(ThreadProc);
                t.Start();
                //backgroundWorker1.RunWorkerAsync();
            }         
        }

        private void LoginFormClosed(object sender, FormClosedEventArgs e)
        {
            //if (IsLoginned)
            //{
            //    _ownerForm.ConfigSecurity();
            //}
            Application.ExitThread();
            Application.Exit();
        }

        #region Nested type: LoginStatus

        private enum LoginStatus
        {
            Successful,
            Fail,
            Wrong
        }

        #endregion

        #region Event Handlers

        private void btnLogin_Click(object sender, EventArgs e)
        {
            string userName = txtUserName.Text.Trim();
            if (userName == string.Empty)
            {
                lblMsg.Text = "Vui lòng nhập Tên đăng nhập.";
                return;
            }

            string password = txtPassword.Text.Trim();
            if (txtPassword.Text == string.Empty)
            {
                lblMsg.Text = "Vui lòng nhập Mật khẩu.";
                return;
            }

            password = Utils.Encrypt(password);
            EnableControls(false);
            var args = new[] {userName, password};
            _backgroundWorker.RunWorkerAsync(args);
        }

        private void txtUserName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnLogin_Click(sender, e);
            }
        }

        private void txtPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnLogin_Click(sender, e);
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            if (!IsLoginned)
            {
                Application.ExitThread();
                Application.Exit();
            }
        }

        #endregion

        #region Private methods

        private void EnableControls(bool isEnable)
        {
            txtPassword.Enabled = isEnable;
            txtUserName.Enabled = isEnable;
            btnLogin.Enabled = isEnable;
            btnClose.Enabled = isEnable;
            pcbLoading.Visible = !isEnable;
            lblLogin.Visible = !isEnable;
        }

        #endregion
        
        public void LoadMainForm()
        {
            MainForm main = this.Owner as MainForm;
            Application.DoEvents();
            main.LoadMainPane();
        }

    }
}